/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.func;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.beust.jcommander.Strings;
import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.util.MessageUtils;
import com.je.common.base.util.SecurityUserHolder;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.service.func.MetaFuncRelyonService;
import com.je.rbac.rpc.PermissionRpcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/je/meta/resButton")
public class ResButtonController extends AbstractPlatformController {

    @Autowired
    private MetaFuncRelyonService funcRelyonService;
    @Autowired
    private MetaService metaService;
    @Autowired
    private PermissionRpcService permissionRpcService;

    /**
     * TODO未处理
     *
     * @param param
     */
    @RequestMapping(value = "/doSave", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doSave(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String RESOURCEBUTTON_CODE = dynaBean.getStr("RESOURCEBUTTON_CODE");
        if (StringUtil.isEmpty(RESOURCEBUTTON_CODE)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("function.button.code.not.empty"));
        }

        List<DynaBean> list = metaService.select("JE_CORE_RESOURCEBUTTON", ConditionsWrapper.builder()
                .eq("RESOURCEBUTTON_FUNCINFO_ID", dynaBean.getStr("RESOURCEBUTTON_FUNCINFO_ID"))
                .eq("RESOURCEBUTTON_CODE", dynaBean.getStr("RESOURCEBUTTON_CODE")));
        if (list != null && list.size() > 0) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.code.repeat", dynaBean.getStr("RESOURCEBUTTON_CODE")));
        }
        /*boolean matches = RESOURCEBUTTON_CODE.matches("^[A-Z]{1}[A-Z_0-9]{0,100}$");
        if (!matches) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("function.button.code.regrex.message"));
        }*/
        dynaBean.set("RESOURCEBUTTON_HIDDEN", "0");
        dynaBean.set("RESOURCEBUTTON_DISABLED", "0");
        dynaBean.set("RESOURCEBUTTON_FORMBIND", "0");
        dynaBean.set("SY_ORDERINDEX", "0");
        //使用范围
        dynaBean.set("RESOURCEBUTTON_USE_SCOPE", "PC");
        if (!"ACTION".equals(dynaBean.getStr("RESOURCEBUTTON_TYPE"))) {
            dynaBean.setStr("RESOURCEBUTTON_BGCOLOR", "#FFFFFF");
            dynaBean.setStr("RESOURCEBUTTON_FONTCOLOR", "#3F3F3F");
            dynaBean.setStr("RESOURCEBUTTON_BORDERCOLOR", "#D9D9D9");
        }
        DynaBean inserted = commonService.doSave(dynaBean);
        //处理依赖功能
        funcRelyonService.doSave("JE_CORE_RESOURCEBUTTON", inserted.getStr("RESOURCEBUTTON_FUNCINFO_ID"), inserted);
        return BaseRespResult.successResult(inserted);
    }

    /**
     * @param param
     */
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doUpdate(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        DynaBean oldBtn = metaService.selectOneByPk("JE_CORE_RESOURCEBUTTON", dynaBean.getStr("JE_CORE_RESOURCEBUTTON_ID"));
        commonService.buildModelModifyInfo(dynaBean);
        metaService.update(dynaBean);
        funcRelyonService.doUpdate("JE_CORE_RESOURCEBUTTON", dynaBean.getStr("RESOURCEBUTTON_FUNCINFO_ID"), funcRelyonService.getUpdateBean("JE_CORE_RESOURCEBUTTON", dynaBean, oldBtn));
        return BaseRespResult.successResult(dynaBean);
    }

    /**
     * 数据更新
     *
     * @param param
     */
    @RequestMapping(value = "/doUpdateList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    @Transactional
    public BaseRespResult doUpdateList(BaseMethodArgument param, HttpServletRequest request) {
        String strData = param.getStrData();
        String funcId = param.getFuncId();

        DynaBean funcInfoBean = metaService.selectOneByPk("JE_CORE_FUNCINFO",funcId);

        //-----------开始，找到变更的按钮,并修改其权限编码为最新的权限编码-----------
        JSONArray strJsonArr = JSON.parseArray(strData);
        List<String> codeIdList = new ArrayList<>();
        for (int i = 0; i < strJsonArr.size(); i++) {
            if (strJsonArr.getJSONObject(i).containsKey("JE_CORE_RESOURCEBUTTON_ID")
                    && !Strings.isStringEmpty(strJsonArr.getJSONObject(i).getString("JE_CORE_RESOURCEBUTTON_ID"))) {
                codeIdList.add(strJsonArr.getJSONObject(i).getString("JE_CORE_RESOURCEBUTTON_ID"));
            }
        }

        if (!codeIdList.isEmpty()) {
            List<DynaBean> oldButtonBeanList = metaService.select("JE_CORE_RESOURCEBUTTON", ConditionsWrapper.builder().in("JE_CORE_RESOURCEBUTTON_ID", codeIdList));
            for (DynaBean eachOldButtonBean : oldButtonBeanList) {
                for (int i = 0; i < strJsonArr.size(); i++) {
                    if (eachOldButtonBean.getStr("JE_CORE_RESOURCEBUTTON_ID").equals(strJsonArr.getJSONObject(i).getString("JE_CORE_RESOURCEBUTTON_ID"))) {
                        if (strJsonArr.getJSONObject(i).containsKey("RESOURCEBUTTON_CODE")
                                && !Strings.isStringEmpty(strJsonArr.getJSONObject(i).getString("RESOURCEBUTTON_CODE"))
                                && !eachOldButtonBean.getStr("RESOURCEBUTTON_CODE").equals(strJsonArr.getJSONObject(i).getString("RESOURCEBUTTON_CODE"))) {
                            permissionRpcService.modifyFuncButtonPermCode(funcInfoBean.getStr("FUNCINFO_FUNCCODE"), eachOldButtonBean.getStr("RESOURCEBUTTON_CODE"), strJsonArr.getJSONObject(i).getString("RESOURCEBUTTON_CODE"));
                        }
                    }
                }
            }
        }
        //-----------结束，找到变更的按钮,并修改其权限编码为最新的权限编码-----------

        List<DynaBean> updateList = commonService.doUpdateList("JE_CORE_RESOURCEBUTTON", strData, null, null);
        funcRelyonService.doUpdateList("JE_CORE_RESOURCEBUTTON", "", updateList);


        return BaseRespResult.successResult(updateList.size() + "条记录被更新!");
    }

    /**
     * TODO未处理
     *
     * @param param
     */
    @RequestMapping(value = "/doRemove", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doRemove(BaseMethodArgument param, HttpServletRequest request) {
        String ids = param.getIds();
        funcRelyonService.doRemove("JE_CORE_RESOURCEBUTTON", null, ids, null);
        int delNum = manager.doRemove(param, request);
        return BaseRespResult.successResult(delNum + "条记录被删除!");
    }

    /**
     * TODO未处理
     *
     * @param param
     */
    @RequestMapping(value = "/initShBtnInfo", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult initShBtnInfo(BaseMethodArgument param, HttpServletRequest request) {
        String funcId = getStringParameter(request, "funcId");
        DynaBean funcInfo = metaService.selectOneByPk("JE_CORE_FUNCINFO", funcId);
        String pkCode = funcInfo.getStr("FUNCINFO_PKNAME");
        long count = metaService.countBySql(ConditionsWrapper.builder().table("JE_CORE_RESOURCEBUTTON")
                .apply("RESOURCEBUTTON_FUNCINFO_ID={0} AND RESOURCEBUTTON_CODE IN ('formSubmitBtn','formCacelBtn')", funcId));
        if (count <= 0) {
            DynaBean formSave = new DynaBean("JE_CORE_RESOURCEBUTTON", false);
            formSave.set(BeanService.KEY_PK_CODE, "JE_CORE_RESOURCEBUTTON_ID");
            formSave.set("RESOURCEBUTTON_CODE", "formSubmitBtn");
            formSave.set("RESOURCEBUTTON_NAME", "审核");
            //可用   true
            formSave.set("RESOURCEBUTTON_DISABLED", "0");
            //表单按钮
            formSave.set("RESOURCEBUTTON_ISFORM", "1");
            formSave.set("RESOURCEBUTTON_HIDDEN", "0");
            formSave.set("RESOURCEBUTTON_TYPE", "FORM");
            ;
            formSave.set("RESOURCEBUTTON_BIGICONCLS", "list_save_32_3");
            //绑定表单验证   false
            formSave.set("RESOURCEBUTTON_FORMBIND", "1");
            //按钮样式
            formSave.set("RESOURCEBUTTON_ICONCLS", "jeicon jeicon-pass");
            formSave.set("RESOURCEBUTTON_FONTICONCLS", "fa fa-arrow-right");
            formSave.set("RESOURCEBUTTON_CLS", "JEPLUS_B_C01");
            formSave.set("SY_ORDERINDEX", 8);
            formSave.set("RESOURCEBUTTON_SYSMODE", "");
            formSave.set("RESOURCEBUTTON_FUNCINFO_ID", funcId);
            formSave.set("RESOURCEBUTTON_INTERPRETER", "JE.isNotEmpty('{" + pkCode + "}') && '1'!='{SY_ACKFLAG}' ");
            commonService.buildModelCreateInfo(formSave);
            metaService.insert(formSave);
            DynaBean cacelBtn = new DynaBean("JE_CORE_RESOURCEBUTTON", false);
            cacelBtn.set(BeanService.KEY_PK_CODE, "JE_CORE_RESOURCEBUTTON_ID");
            cacelBtn.set("RESOURCEBUTTON_CODE", "formCacelBtn");
            cacelBtn.set("RESOURCEBUTTON_NAME", "撤销审核");
            //可用   true
            cacelBtn.set("RESOURCEBUTTON_DISABLED", "0");
            //表单按钮
            cacelBtn.set("RESOURCEBUTTON_ISFORM", "1");
            cacelBtn.set("RESOURCEBUTTON_HIDDEN", "0");
            cacelBtn.set("RESOURCEBUTTON_TYPE", "FORM");
            cacelBtn.set("RESOURCEBUTTON_BIGICONCLS", "list_save_32_3");
            //绑定表单验证   false
            cacelBtn.set("RESOURCEBUTTON_FORMBIND", "1");
            //按钮样式
            cacelBtn.set("RESOURCEBUTTON_ICONCLS", "JE_WF_BACK");
            cacelBtn.set("RESOURCEBUTTON_FONTICONCLS", "fa fa-repeat");
            cacelBtn.set("RESOURCEBUTTON_CLS", "JEPLUS_B_C01");
            cacelBtn.set("SY_ORDERINDEX", 9);
            cacelBtn.set("RESOURCEBUTTON_SYSMODE", "");
            cacelBtn.set("RESOURCEBUTTON_FUNCINFO_ID", funcId);
            cacelBtn.set("RESOURCEBUTTON_INTERPRETER", "JE.isNotEmpty('{" + pkCode + "}') && '1'=='{SY_ACKFLAG}' ");
            commonService.buildModelCreateInfo(cacelBtn);
            metaService.insert(cacelBtn);
            return BaseRespResult.successResult(null, "审核按钮初始化成功!");
        } else {
            return BaseRespResult.errorResult("该功能已经包含审核按钮!");
        }
    }

}
